<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div slot="header" class="profile-header">
        <span>个人档案</span>
        <el-button 
          type="text" 
          icon="el-icon-edit"
          @click="startEditing"
          v-if="!isEditing">
          编辑资料
        </el-button>
      </div>

      <!-- 用户基本信息展示区域 -->
      <div class="user-info-section">
        <div class="user-avatar">
          <el-avatar :size="100" icon="el-icon-user-solid"></el-avatar>
          <div class="user-name">{{ profileData.fullName || '未设置姓名' }}</div>
          <div class="user-tag">{{ profileData.roleTag || '未设置角色' }}</div>
        </div>

        <div class="user-details">
          <!-- 非编辑模式下的信息展示 -->
          <template v-if="!isEditing">
            <div class="detail-item">
              <i class="el-icon-user"></i>
              <span class="label">姓名：</span>
              <span class="value">{{ profileData.fullName || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-phone"></i>
              <span class="label">手机号码：</span>
              <span class="value">{{ profileData.phoneNumber || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-medal"></i>
              <span class="label">角色类型：</span>
              <span class="value">{{ profileData.roleTag || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-data-line"></i>
              <span class="label">身高：</span>
              <span class="value">{{ profileData.height ? `${profileData.height} cm` : '未设置' }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-data-analysis"></i>
              <span class="label">体重：</span>
              <span class="value">{{ profileData.weight ? `${profileData.weight} kg` : '未设置' }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-time"></i>
              <span class="label">年龄：</span>
              <span class="value">{{ profileData.age ? `${profileData.age} 岁` : '未设置' }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-male"></i>
              <span class="label">性别：</span>
              <span class="value">{{ formatGender(profileData.gender) }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-date"></i>
              <span class="label">注册时间：</span>
              <span class="value">{{ formatDate(profileData.createdAt) }}</span>
            </div>
          </template>

          <!-- 编辑模式下的表单 -->
          <el-form 
            v-else 
            :model="editForm" 
            :rules="rules" 
            ref="editForm" 
            label-width="100px"
            class="edit-form">
            
            <el-form-item label="姓名" prop="fullName">
              <el-input v-model="editForm.fullName" placeholder="请输入您的姓名"></el-input>
            </el-form-item>
            
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="editForm.phoneNumber" placeholder="请输入您的手机号码"></el-input>
            </el-form-item>
            
            <el-form-item label="角色类型" prop="roleTag">
              <el-select v-model="editForm.roleTag" placeholder="请选择您的角色类型">
                <el-option label="健康追求者" value="健康追求者"></el-option>
                <el-option label="健身爱好者" value="健身爱好者"></el-option>
                <el-option label="慢性病患者" value="慢性病患者"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="身高(cm)" prop="height">
              <el-input-number v-model="editForm.height" :precision="1" :step="0.1" :min="50" :max="250"></el-input-number>
            </el-form-item>
            
            <el-form-item label="体重(kg)" prop="weight">
              <el-input-number v-model="editForm.weight" :precision="1" :step="0.1" :min="20" :max="300"></el-input-number>
            </el-form-item>
            
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="editForm.age" :min="1" :max="120"></el-input-number>
            </el-form-item>
            
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="editForm.gender">
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
                <el-radio label="other">其他</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveProfile" :loading="loading">保存更改</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 健康指标区域 -->
      <div class="health-indicators" v-if="!isEditing && profileData.height && profileData.weight">
        <h3>健康指标</h3>
        <div class="indicators-container">
          <div class="indicator-item">
            <div class="indicator-value">{{ calculateBMI().value }}</div>
            <div class="indicator-name">BMI指数</div>
            <div class="indicator-status" :class="calculateBMI().class">{{ calculateBMI().status }}</div>
          </div>
          
          <div class="indicator-item">
            <div class="indicator-value">{{ calculateIdealWeight() }} kg</div>
            <div class="indicator-name">理想体重</div>
            <div class="indicator-status" :class="calculateWeightDifference().class">
              {{ calculateWeightDifference().text }}
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'ProfileView',
  data() {
    // 手机号码验证规则
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (value && !phoneRegex.test(value)) {
        callback(new Error('请输入有效的11位手机号码'));
      } else {
        callback();
      }
    };
    
    return {
      isEditing: false,
      loading: false,
      profileData: {
        id: null,
        userId: null,
        fullName: '',
        phoneNumber: '',
        roleTag: '',
        height: null,
        weight: null,
        age: null,
        gender: '',
        createdAt: null,
        updatedAt: null
      },
      editForm: {
        id: null,
        userId: null,
        fullName: '',
        phoneNumber: '',
        roleTag: '',
        height: null,
        weight: null,
        age: null,
        gender: ''
      },
      rules: {
        fullName: [
          { required: true, message: '请输入您的姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        roleTag: [
          { required: true, message: '请选择您的角色类型', trigger: 'change' }
        ],
        height: [
          { required: true, message: '请输入您的身高', trigger: 'blur' }
        ],
        weight: [
          { required: true, message: '请输入您的体重', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入您的年龄', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择您的性别', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.fetchUserProfile();
  },
  methods: {
    // 获取用户资料
    fetchUserProfile() {
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
      if (userInfo.id) {
        this.axios.get(`/api/userProfile/get`)
          .then(response => {
            if (response.data && response.data.id) {
              // 用户资料存在，显示资料
              this.profileData = response.data;
            } else {
              // 用户资料不存在，引导用户填写
              this.$message.warning('请先完善您的个人资料');
              this.$router.replace('/profile-form');
            }
          })
          .catch(error => {
            console.error('获取用户资料失败:', error);
            this.$message.error('获取用户资料失败，请稍后再试');
            
            // 可以选择性地重定向到资料填写页面
            this.$router.replace('/profile-form');
          });
      } else {
        this.$message.warning('用户未登录');
        this.$router.replace('/');
      }
    },
    
    // 开始编辑
    startEditing() {
      this.editForm = { ...this.profileData };
      this.isEditing = true;
    },
    
    // 取消编辑
    cancelEdit() {
      this.isEditing = false;
      this.$message({
        message: '已取消编辑',
        type: 'info'
      });
    },
    
    // 保存编辑后的资料
    saveProfile() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          
          this.axios({
            url: '/api/userProfile/update',
            method: 'put',
            data: this.editForm
          })
            .then(response => {
              this.loading = false;
              this.isEditing = false;
              this.profileData = { ...this.editForm };
              
              this.$message({
                message: '个人资料更新成功',
                type: 'success'
              });
            })
            .catch(error => {
              this.loading = false;
              console.error('更新用户资料失败:', error);
              this.$message.error('更新失败，请稍后再试');
            });
        }
      });
    },
    
    // 格式化性别显示
    formatGender(gender) {
      if (!gender) return '未设置';
      const genderMap = {
        'male': '男',
        'female': '女',
        'other': '其他'
      };
      return genderMap[gender] || gender;
    },
    
    // 格式化日期显示
    formatDate(dateString) {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    // 计算BMI指数
    calculateBMI() {
      if (!this.profileData.height || !this.profileData.weight) {
        return { value: '未知', status: '未知', class: '' };
      }
      
      const heightInM = this.profileData.height / 100;
      const bmi = this.profileData.weight / (heightInM * heightInM);
      const roundedBMI = parseFloat(bmi.toFixed(1));
      
      let status = '';
      let statusClass = '';
      
      if (bmi < 18.5) {
        status = '偏瘦';
        statusClass = 'status-warning';
      } else if (bmi >= 18.5 && bmi < 24) {
        status = '正常';
        statusClass = 'status-success';
      } else if (bmi >= 24 && bmi < 28) {
        status = '超重';
        statusClass = 'status-warning';
      } else {
        status = '肥胖';
        statusClass = 'status-danger';
      }
      
      return { value: roundedBMI, status: status, class: statusClass };
    },
    
    // 计算理想体重
    calculateIdealWeight() {
      if (!this.profileData.height) return '未知';
      
      // 使用公式：男性：(身高cm-80)×70﹪ 女性：(身高cm-70)×60﹪
      const height = this.profileData.height;
      let idealWeight;
      
      if (this.profileData.gender === 'male') {
        idealWeight = (height - 80) * 0.7;
      } else {
        idealWeight = (height - 70) * 0.6;
      }
      
      return parseFloat(idealWeight.toFixed(1));
    },
    
    // 计算体重差异
    calculateWeightDifference() {
      if (!this.profileData.height || !this.profileData.weight) {
        return { text: '未知', class: '' };
      }
      
      const idealWeight = this.calculateIdealWeight();
      const difference = this.profileData.weight - idealWeight;
      
      let text = '';
      let statusClass = '';
      
      if (Math.abs(difference) <= 2) {
        text = '体重理想';
        statusClass = 'status-success';
      } else if (difference > 2) {
        text = `偏重${difference.toFixed(1)}kg`;
        statusClass = 'status-warning';
      } else {
        text = `偏轻${Math.abs(difference).toFixed(1)}kg`;
        statusClass = 'status-warning';
      }
      
      return { text, class: statusClass };
    }
  }
};
</script>

<style scoped>
.profile-container {
  display: flex;
  justify-content: center;
  padding: 40px 20px;
  min-height: 100vh;
  background: linear-gradient(120deg, #e3f2fd, #bbdefb, #fce4ec, #f8bbd0);
}

.profile-card {
  width: 100%;
  max-width: 800px;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(33, 150, 243, 0.1);
  background: linear-gradient(to bottom, #ffffff, #f8f8ff);
  border: 1px solid rgba(33, 150, 243, 0.2);
  overflow: hidden;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #2196f3;
}

.profile-header .el-button--text {
  padding: 0;
  font-size: 14px;
  color: #ff9a9e;
}

.user-info-section {
  display: flex;
  flex-wrap: wrap;
  padding: 20px 0;
  border-bottom: 1px dashed #e0e0e0;
}

.user-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 40px;
  margin-bottom: 20px;
  min-width: 140px;
}

.user-name {
  margin-top: 15px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.user-tag {
  margin-top: 8px;
  padding: 4px 12px;
  background-color: #e3f2fd;
  color: #2196f3;
  border-radius: 20px;
  font-size: 12px;
}

.user-details {
  flex: 1;
  min-width: 300px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item i {
  font-size: 18px;
  color: #2196f3;
  margin-right: 10px;
  width: 24px;
  text-align: center;
}

.detail-item .label {
  width: 80px;
  color: #666;
  font-weight: 500;
}

.detail-item .value {
  flex: 1;
  color: #333;
}

.edit-form {
  padding-top: 15px;
}

.health-indicators {
  margin-top: 30px;
  padding-top: 20px;
}

.health-indicators h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #2196f3;
  font-weight: 600;
}

.indicators-container {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.indicator-item {
  padding: 20px;
  min-width: 150px;
  text-align: center;
  border-radius: 10px;
  background-color: #f5f9ff;
  margin-bottom: 15px;
  transition: all 0.3s;
  box-shadow: 0 4px 10px rgba(33, 150, 243, 0.1);
}

.indicator-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(33, 150, 243, 0.15);
}

.indicator-value {
  font-size: 24px;
  font-weight: bold;
  color: #2196f3;
  margin-bottom: 8px;
}

.indicator-name {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.indicator-status {
  display: inline-block;
  padding: 3px 10px;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 500;
}

.status-success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-danger {
  background-color: #fef0f0;
  color: #f56c6c;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .user-info-section {
    flex-direction: column;
    align-items: center;
  }
  
  .user-avatar {
    margin-right: 0;
    margin-bottom: 30px;
  }
  
  .user-details {
    width: 100%;
  }
}
</style> 